<template>
  <a-select
    showSearch
    labelInValue
    :disabled="disabled"
    :getPopupContainer="getParentContainer"
    @search="searchLoadData"
    :placeholder="placeholder"
    :value="selectedAsyncValue"
    style="width: 100%"
    :filterOption="false"
    @change="handleAsyncChange"
    :allowClear="allowClear"
    :showArrow="false"
    :notFoundContent="loading ? undefined : null"
  >
    <a-spin v-if="loading" slot="notFoundContent" size="small"/>
    <a-select-option v-for="d in options" :key="d.value" :value="d.value">{{ d.text }}</a-select-option>
  </a-select>
</template>

<script>
  import { ajaxGetDictItems,getDictItemsFromCache } from '@/api/api'
  import { getAction } from '@/api/manage'
  import { simpleDebounce } from '@/utils/util'
  export default {
    name: 'JSearchSelectUser',
    props:{
      disabled: Boolean,
      value: [String, Number],
      dictOptions: Array,
      placeholder:{
        type:String,
        default:"请输入并选择",
        required:false
      },
      dict:{
        type: String,
        default: "sys_user,username,username",
        required: false
      },
      allowClear: {
        type: Boolean,
        default:true
      },
      popContainer:{
        type:String,
        default:'',
        required:false
      },
      pageSize:{
        type: Number,
        default: 20,
        required: false
      },
      getPopupContainer: {
        type:Function,
        default: null
      },
    // 自定义返回字段，默认返回姓名'name''  如需要返回id 的话传'id''
    //  customReturnField: {
    //    type: String,
    //    default:'name'
    //  },
    },
    data(){
      // this.loadData = debounce(this.loadData, 800);//消抖
      this.lastLoad = 0;
      return {
        loading:false,
        selectedValue:[],
        selectedAsyncValue:[],
        options: [], 
      }
    },
    created(){
 
    },
    watch:{
      "value":{
        immediate:true,
        handler(val) {
          if (val) {
            this.initSelectValue()
          } else { 
            this.selectedValue = []
            this.selectedAsyncValue = []
            this.options=[] 
          }
        }
      },
      "dict":{
        handler() {
          this.initDictData()
        }
      },

    },
    methods:{
      initSelectValue() {
          if(!this.selectedAsyncValue || !this.selectedAsyncValue.key || this.selectedAsyncValue.key!=this.value){
            getAction(`/sys/dict/loadDictItem/${this.dict}`, { key: this.value}).then(res => {
              if (res.success) {
                if (res.result) {
                  let obj = {
                    key: this.value,
                    label: res.result
                  }
                  this.selectedAsyncValue = { ...obj }
                }
              } else { 
                 this.$message.warning(res.message);
              }
            })     
        } 
      },
      searchLoadData: simpleDebounce(function (value) {
        this.loadData(value)
      }, 500),
      loadData(value) {
        if (value) {
          this.lastLoad += 1
          const currentLoad = this.lastLoad
          this.options = []
          this.loading = true
          // 字典code格式：table,text,code
          // sys_user,username,username,status=1
          getAction(`/sys/dict/loadDict/${this.dict},status=1`, { keyword: value, pageSize: this.pageSize }).then(res => {
            this.loading = false
            if (res.success) {
              if (currentLoad != this.lastLoad) {
                return
              }
              this.options = res.result ? res.result :[]
            } else {
              this.$message.warning(res.message)
            }
          })
        } else { 
           this.options = []
        }
      },
      initDictData(){
          if(!this.dict){
            console.error('搜索组件未配置字典项')
          } else {
            //异步一开始也加载一点数据
            this.loading=true
            getAction(`/sys/dict/loadDict/${this.dict}`,{pageSize: this.pageSize, keyword:''}).then(res=>{
              this.loading=false
              if(res.success){
                this.options = res.result ? res.result :[]
              }else{
                this.$message.warning(res.message)
              }
            })
          }
      },
      // filterOption(input, option) {
      //   return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      // },
      // handleChange (selectedValue) {
      //   console.log("selectedValue",selectedValue)
      //   this.selectedValue = selectedValue
      //   this.callback()
      // },
      handleAsyncChange(selectedObj){
        if(selectedObj){
          this.selectedAsyncValue = selectedObj
          this.selectedValue = selectedObj.key
        }else{
          this.selectedAsyncValue = null
          this.selectedValue = null
          this.options = null
        }
        this.callback()
      },
      callback(){
        this.$emit('change', this.selectedValue);
      },
      setCurrentDictOptions(dictOptions){
        this.options = dictOptions
      },
      getCurrentDictOptions(){
        return this.options
      },
      getParentContainer(node){
        if(typeof this.getPopupContainer === 'function'){
          return this.getPopupContainer(node)
        } else if(!this.popContainer){
          return node.parentNode
        }else{
          return document.querySelector(this.popContainer)
        }
      },

    },
    model: {
      prop: 'value',
      event: 'change'
    }
  }
</script>

<style scoped>

</style>